package cas.ihep.hdfs;

import com.google.common.io.Closer;
import org.apache.hadoop.hdfs.protocol.HdfsFileStatus;

import java.io.Closeable;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public abstract class HdfsFile implements Closeable,Iterable<HdfsBlock> {

    protected HdfsSystem mFs;
    protected String mFilepath;
    //LocatedBlocks mBlocks;
    protected Closer mCloser;
    protected List<HdfsBlock> mBlocks;
    private boolean mClosed;
    protected HdfsFileStatus mMetadata;

    public HdfsFile(HdfsSystem fs,String path)throws IOException {
        mFs=fs;
        mFilepath=path;
        mClosed=false;
        mCloser= Closer.create();
        mMetadata = mFs.mClient.getFileInfo(path);
        mBlocks=new ArrayList<>();
    }

    public abstract HdfsBlock getBlock(int idx)throws IOException;

    public List<HdfsBlock> blocks(){
        return mBlocks;
    }

    public void close()throws IOException {
        if (!mClosed){
            mClosed=true;
            mCloser.close();
        }
    }

    @Override
    public Iterator<HdfsBlock> iterator() {
        return mBlocks.iterator();
    }

    public String getPath(){
        return mFilepath;
    }

    public abstract long getLength();
    public abstract HdfsFile open()throws IOException;
    public abstract boolean canRead()throws IOException;
    public abstract boolean carWrite()throws IOException;
}